<script setup>
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElButton, ElIcon, ElDialog, ElForm, ElFormItem, ElInput, ElPagination, ElMessageBox, ElNotification } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh, Download, Filter, Check, Close } from '@element-plus/icons-vue'

// 课程分类列表数据
const categoryList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 当前页码
const currentPage = ref(1)
// 每页条数
const pageSize = ref(10)
// 总条数
const total = ref(0)
// 加载状态
const loading = ref(false)
// 编辑对话框显示状态
const editDialogVisible = ref(false)
// 编辑表单数据
const editForm = ref({
  id: '',
  name: '',
  description: ''
})
// 新增对话框显示状态
const addDialogVisible = ref(false)
// 新增表单数据
const addForm = ref({
  name: '',
  description: ''
})
// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入分类描述', trigger: 'blur' }]
}

// 加载课程分类列表
const loadCategoryList = async () => {
  loading.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    // 模拟数据
    const mockData = Array.from({ length: 15 }, (_, index) => ({
      id: index + 1,
      name: ['必修课', '选修课', '通识课', '专业课', '公共课', '基础课', '实践课', '理论课', '研讨课', '实验课', '线上课', '线下课', '混合课', '核心课', '拓展课'][index],
      description: `这是${['必修课', '选修课', '通识课', '专业课', '公共课', '基础课', '实践课', '理论课', '研讨课', '实验课', '线上课', '线下课', '混合课', '核心课', '拓展课'][index]}的详细描述。`,
      courseCount: Math.floor(Math.random() * 10) + 1
    }))

    // 筛选数据
    let filteredData = mockData
    if (searchKeyword.value) {
      filteredData = mockData.filter(item =>
        item.name.includes(searchKeyword.value) ||
        item.description.includes(searchKeyword.value)
      )
    }

    // 分页
    total.value = filteredData.length
    categoryList.value = filteredData.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    )
  } catch (error) {
    ElNotification.error('获取课程分类列表失败')
    console.error('Failed to load category list:', error)
  } finally {
    loading.value = false
  }
}

// 搜索课程分类
const searchCategories = () => {
  currentPage.value = 1
  loadCategoryList()
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  loadCategoryList()
}

// 打开编辑对话框
const openEditDialog = (row) => {
  editForm.value = { ...row }
  editDialogVisible.value = true
}

// 关闭编辑对话框
const closeEditDialog = () => {
  editDialogVisible.value = false
}

// 保存编辑
const saveEdit = async () => {
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    // 查找并更新数据
    const index = categoryList.value.findIndex(item => item.id === editForm.value.id)
    if (index !== -1) {
      categoryList.value.splice(index, 1, { ...editForm.value })
    }
    ElNotification.success('编辑成功')
    closeEditDialog()
  } catch (error) {
    ElNotification.error('编辑失败')
    console.error('Failed to save edit:', error)
  }
}

// 打开新增对话框
const openAddDialog = () => {
  addForm.value = {
    name: '',
    description: ''
  }
  addDialogVisible.value = true
}

// 关闭新增对话框
const closeAddDialog = () => {
  addDialogVisible.value = false
}

// 保存新增
const saveAdd = async () => {
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    // 生成新ID
    const newId = Math.max(...categoryList.value.map(item => item.id), 0) + 1
    // 添加新数据
    categoryList.value.unshift({
      id: newId,
      ...addForm.value,
      courseCount: 0
    })
    total.value++
    ElNotification.success('添加成功')
    closeAddDialog()
  } catch (error) {
    ElNotification.error('添加失败')
    console.error('Failed to save add:', error)
  }
}

// 删除课程分类
const deleteCategory = async (id) => {
  try {
    const result = await ElMessageBox.confirm('确定要删除该课程分类吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (result === 'confirm') {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 500))
      // 删除数据
      categoryList.value = categoryList.value.filter(item => item.id !== id)
      total.value--
      ElNotification.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElNotification.error('删除失败')
      console.error('Failed to delete category:', error)
    }
  }
}

// 查看分类详情
const viewCategoryDetail = (id) => {
  // 实际应用中这里应该跳转到分类详情页
  ElNotification.info('跳转到分类详情页')
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadCategoryList()
}

// 当前页变化
const handleCurrentChange = (current) => {
  currentPage.value = current
  loadCategoryList()
}

// 页面加载时获取数据
onMounted(() => {
  loadCategoryList()
})
</script>

<template>
  <div class="category-list-container">
    <div class="header">
      <h2>课程分类管理</h2>
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入分类名称或描述"
          prefix-icon="Search"
          style="width: 300px; margin-right: 10px;"
        />
        <el-button type="primary" @click="searchCategories">
          <el-icon><Search /></el-icon> 搜索
        </el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="action-buttons">
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon> 新增
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
        <el-button @click="downloadData">
          <el-icon><Download /></el-icon> 导出
        </el-button>
        <el-button @click="showFilter">
          <el-icon><Filter /></el-icon> 筛选
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="categoryList"
      style="width: 100%;"
      border
    >
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="name" label="分类名称" width="180">
        <template #default="{ row }">
          <span @click="viewCategoryDetail(row.id)" class="category-name-link">{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="分类描述" width="300" />
      <el-table-column prop="courseCount" label="课程数量" width="120" align="center" />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="openEditDialog(row)">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-button type="danger" size="small" @click="deleteCategory(row.id)">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑课程分类" width="500px">
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input v-model="editForm.description" type="textarea" placeholder="请输入分类描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button type="primary" @click="saveEdit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增课程分类" width="500px">
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input v-model="addForm.description" type="textarea" placeholder="请输入分类描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeAddDialog">取消</el-button>
        <el-button type="primary" @click="saveAdd">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.category-list-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.search-bar {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.category-name-link {
  color: #4096ff;
  cursor: pointer;
  text-decoration: underline;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>